package com.springapp.mvc.utils;

import com.springapp.mvc.constant.SystemConstant;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2016/3/15.
 */
public class MediaUtils {

    /**
     * 获取文件扩展名
     *
     * @return string
     */
    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String save(HttpServletRequest request,MultipartFile multipartFile){
        SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
        String path = "/" + formater.format(new Date()) + "/"
                + UUID.randomUUID().toString().replaceAll("-", "")
                + getFileExt(multipartFile.getOriginalFilename());
        String root = request.getSession().getServletContext().getRealPath("upload");
        File file = new File(root+ "/" + path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        //保存文件
        try {
            multipartFile.transferTo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
}
